package com.nxn.core.web.action.json;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.nxn.core.model.Resources;
import com.nxn.core.model.RoleAuth;
import com.nxn.core.service.UserService;
import com.nxn.core.web.action.base.BaseAction;
import com.nxn.core.web.jsonItems.ZTreeNode;

//@Namespace("/json")
@ParentPackage("ajax-request")
@Results( { @Result(name = "success", type="json", 
		params={"excludeNullProperties","true", "excludeProperties", "password,person.*\\.firstName"}) 
} )
public class DataLoadAction extends BaseAction {
	private static final long serialVersionUID = 704573801857794612L;

	@Autowired
	private UserService userService;

	private String username;
	private List<ZTreeNode> treeNodes;
	
	/** 
	 * used for ZTree AJAX load
	 * @return
	 * @throws Exception
	 */
	public String loadZTree() throws Exception {
//    	String username = getParameterForString("username");
    	
    	treeNodes = new ArrayList<ZTreeNode>();
    	List<RoleAuth> menuResources = userService.findMenuResourceByUsername(username);
    	for (Iterator<RoleAuth> iter = menuResources.iterator(); iter.hasNext();) {
			RoleAuth roleAuth = iter.next();
			
			treeNodes.add(buildZTreeNodeByResource(roleAuth.getResource()));
		}
    	
		return SUCCESS;
	}

	private ZTreeNode buildZTreeNodeByResource(Resources resource) {
		ZTreeNode treeNode = new ZTreeNode();
		
		treeNode.setId(resource.getId());
		treeNode.setName(resource.getDisplayName());
		treeNode.setIconSkin(resource.getIcon());
		/** test UI Layout, ZTree and jqGrid */
		if(resource.getName().equals("customer")) {
			treeNode.setUrl("test/test-customer.action");
		} else {
			treeNode.setUrl(resource.getUrl());
			
		}
		Resources parent = resource.getParent();
		treeNode.setpId(parent!=null?parent.getId():0);
		
		return treeNode;
	}

	public List<ZTreeNode> getTreeNodes() {
		return treeNodes;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}
